package com.jiuyin.dianjing.ui.activity.team;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.HeadPhotoAdapter;
import com.jiuyin.dianjing.api.base.DefaultApiResult;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.interfaces.ProgressDialogCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.model.MatchGameItemModel;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.util.DisplayUtil;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.ToastUtil;
import com.mobsandgeeks.saripaar.annotation.Length;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_GAMEID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_GENRE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_INTRO;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_LOGO;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_NAME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TYPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_UNIVERSITY_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_USERID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_USER_ID;

/**
 * 创建战队
 */
public class CreateTeamActivity extends BaseActivity {
    public final static int REQUEST_GAME = 0;
    public static final int REQUEST_BADGE = 1;
    ArrayList<MatchGameItemModel> selectedGames = new ArrayList<>();
    String selectedBadge = "";
    HeadPhotoAdapter photoAdapter;
    @BindView(R.id.layout_badge)
    View layoutBadge;
    @BindView(R.id.iv_badge)
    ImageView ivBadge;
    @NotEmpty(message = "请填写战队名称")
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_intro)
    @NotEmpty(message = "请填写战队介绍")
    @Length(max = 1024, message = "长度超过最大限制")
    EditText etIntro;
    @BindView(R.id.rg_type)
    RadioGroup rgType;
    @BindView(R.id.tv_college_left)
    TextView tvUserIdLeft;
    @BindView(R.id.tv_college)
    TextView tvUserId;
    @BindView(R.id.tv_username)
    TextView tvUserName;
    @BindView(R.id.rb_college)
    RadioButton rbUserName;
    @BindView(R.id.layout_games)
    View layoutGames;
    @BindView(R.id.rv_games)
    RecyclerView rvGames;
    @BindView(R.id.bt_submit)
    Button btSubmit;
    private String genre = GENRE_0;
    private List<String> selectedGameLogos;
    private String mUniversityId;
    /**
     * 公开赛
     */
    private static String GENRE_0 = "0";
    /**
     * 高校赛
     */
    private static String GENRE_1 = "1";

    @Override
    protected int setLayoutId() {
        return R.layout.activity_create_team;
    }

    @Override
    public void initData() {
        HashMap<String, Object> data = new HashMap<>();
        data.put(KEY_TOKEN, HelperApplication.getToken());
        JSONObject jsonObject = new JSONObject(data);
        ProgressDialogCallback progress = new ProgressDialogCallback() {
            @Override
            public void showProgressDialog() {
                showLoading();
            }

            @Override
            public void dismissProgressDialog() {
                dismissLoading();
            }
        };
        ApiResultCallback request = new ApiResultCallback() {
            @Override
            public void onSuccess(JsonObject data) {
                LogUtil.log("CreateTeamActivity onSuccess = " + data.toString());
                String university_id = data.get(KEY_UNIVERSITY_ID).getAsString();
                String user_id = data.get(KEY_USER_ID).getAsString();
                mUniversityId = university_id;
                if (TextUtils.isEmpty(mUniversityId)) {
                    rbUserName.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFail(String msg) {
                if (TextUtils.isEmpty(mUniversityId)) {
                    rbUserName.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(String msg) {
                if (TextUtils.isEmpty(mUniversityId)) {
                    rbUserName.setVisibility(View.GONE);
                }
            }
        };
        ServerApi.post(ApiEnum.APP_GET_CREATE_TEAM_DATA.getUrl(), jsonObject, null,
                progress, d -> addDisposable(d), request);
    }


    @Override
    protected void initView() {
        setTitle(getString(R.string.match_create_team));
        rvGames.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        photoAdapter = new HeadPhotoAdapter(20f);
        rvGames.setAdapter(photoAdapter);
        layoutGames.setOnClickListener(v -> {
            Intent intent = new Intent(this, GameGridActivity.class);
            intent.putParcelableArrayListExtra("selected", selectedGames);
            startActivityForResult(intent, REQUEST_GAME);
        });
        layoutBadge.setOnClickListener(v -> {
            Intent intent = new Intent(this, BadgeGridActivity.class);
            intent.putExtra("selected", selectedBadge);
            startActivityForResult(intent, REQUEST_BADGE);
        });
        rgType.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_college:
                    tvUserIdLeft.setText("高校ID");
                    tvUserId.setText(mUniversityId);
                    genre = GENRE_1;
                    break;
                case R.id.rb_open:
                    tvUserIdLeft.setText("用户ID");
                    tvUserId.setText(HelperApplication.getUserId());
                    genre = GENRE_0;
                    break;
            }
        });
        rgType.check(R.id.rb_open);
        tvUserName.setText(HelperApplication.getNickName());
        btSubmit.setOnClickListener(v -> {
            submit();
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case REQUEST_BADGE:
                    selectedBadge = data.getStringExtra("selected");
                    Glide.with(this)
                            .load(selectedBadge)
                            .override(DisplayUtil.dp2px(this, 43.3f))
                            .into(ivBadge);
                    break;
                case REQUEST_GAME:
                    selectedGames = data.getParcelableArrayListExtra("selected");
                    selectedGameLogos = new ArrayList<>();
                    for (MatchGameItemModel selectedGame : selectedGames) {
                        selectedGameLogos.add(selectedGame.getLogo());
                    }
                    photoAdapter.setData(selectedGameLogos);
                    break;
            }
        }
    }

    private void submit() {
        if (selectedGames.size() == 0) {
            ToastUtil.showShort("请选择游戏类型");
            return;
        }
        checkTeamNameExist();
    }

    /**
     * 检查战队是否重复
     *
     * @return
     */
    private void checkTeamNameExist() {
        HashMap hashMap = new HashMap();
        hashMap.put(KEY_NAME, etName.getText().toString());
        JSONObject jsonObject = new JSONObject(hashMap);
        final ApiResultCallback requestCallback1 = new DefaultApiResult() {
            @Override
            public void onSuccess(JsonObject data) {
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < selectedGames.size(); i++) {
                    stringBuilder.append(selectedGames.get(i).getGameId());
                    if (i < selectedGames.size() - 1) {
                        stringBuilder.append(",");
                    }
                }
                HashMap hashMap = new HashMap();
                hashMap.put(KEY_NAME, etName.getText().toString());
                hashMap.put(KEY_LOGO, selectedBadge);
                hashMap.put(KEY_GAMEID, stringBuilder.toString());
                hashMap.put(KEY_INTRO, etIntro.getText().toString());
                hashMap.put(KEY_GENRE, genre);
                hashMap.put(KEY_TOKEN, HelperApplication.getToken());
                JSONObject jsonObjectData = new JSONObject(hashMap);
                getApiHelper().appCreateTeam(jsonObjectData.toString(), data1 -> {
                    btSubmit.setEnabled(true);
                    if (data1) {
                        ToastUtil.showShort(R.string.match_create_team_success);
                        Intent intent = new Intent(CreateTeamActivity.this, MyTeamsActivity.class);
                        intent.putExtra(KEY_TYPE, "1");
                        intent.putExtra(KEY_USERID, "");
                        startActivity(intent);
                        finish();
                    }
                });
            }

            @Override
            public void onFail(String msg) {
                super.onFail(msg);
                LogUtil.log("checkTeamNameExist onFail msg = " + msg);
                ToastUtil.showShort(msg);
                btSubmit.setEnabled(true);
            }

            @Override
            public void onError(String msg) {
                super.onError(msg);
                LogUtil.log("checkTeamNameExist onError msg = " + msg);
                ToastUtil.showShort(msg);
                btSubmit.setEnabled(true);
            }
        };
        btSubmit.setEnabled(false);
        ServerApi.post(ApiEnum.CHECK_NAME_TEAM_BY, jsonObject, null, progress, d -> addDisposable(d), requestCallback1);
    }
}
